package cn.vawn.base.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.util.Properties;

public final class PropertyUtil {
    private static final Logger logger = LoggerFactory.getLogger(PropertyUtil.class);

    private static final String CONFIG_FILE = "app.properties";
    private static final Properties prop = new Properties();

    static {
        InputStream in = null;
        try {
            in = PropertyUtil.class.getClassLoader().getResourceAsStream(CONFIG_FILE);
            BufferedReader bf = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            prop.load(bf);
        } catch (IOException ex) {
            logger.warn("Failed to load application configurations.", ex);
        }
    }

    public static String getString(String key) {
        return prop.getProperty(key);
    }

    public static String getString(String key, String... args) {
        return MessageFormat.format(prop.getProperty(key), (Object[]) args);
    }

    public static int getInt(String key) {
        String val = getString(key);
        int ret = -1;
        try {
            ret = Integer.parseInt(val);
        } catch (Exception ex) {
            logger.warn(String.format("Failed to parse %s to int.", val));
        }
        return ret;
    }

    public static double getDouble(String key) {
        String val = getString(key);
        double ret = -1;
        try {
            ret = Double.parseDouble(val);
        } catch (Exception ex) {
            logger.warn(String.format("Failed to parse %s to double.", val));
        }
        return ret;
    }

    public static boolean getBoolean(String key) {
        return Boolean.getBoolean(getString(key));
    }

    private PropertyUtil() {
    }
}
